import io, sys, time, re, os
import winreg
# coding=utf-8
import winreg


# 处理代理服务器

class ProxyServer:

    def __init__(self):
        self.__path = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings'
        self.__INTERNET_SETTINGS = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                                    self.__path, 0, winreg.KEY_ALL_ACCESS)

    def get_server_form_Win(self):
        """获取代理配置的ip和端口号"""
        ipPort = ""
        if self.is_open_proxy_form_Win():
            try:
                ipPort = winreg.QueryValueEx(self.__INTERNET_SETTINGS, "ProxyServer")[0]
                print("获取到代理信息：{}".format(ipPort))
            except FileNotFoundError as err:
                print("没有找到代理信息：" + str(err))
            except Exception as err:
                print("有其他报错：" + str(err))
        else:
            print("系统没有开启代理")
        return ipPort

    def is_open_proxy_form_Win(self):
        """判断是否开启了代理"""
        try:
            if winreg.QueryValueEx(self.__INTERNET_SETTINGS, "ProxyEnable")[0] == 1:
                return True
        except FileNotFoundError as err:
            print("没有找到代理信息：" + str(err))
        except Exception as err:
            print("有其他报错：" + str(err))
        return False


# 表项路径
xpath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings"
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, xpath, 0, winreg.KEY_WRITE)


# 设定代理,enable:是否开启,proxyIp:代理服务器ip及端口,IgnoreIp:忽略代理的ip或网址
def setProxy(enable, proxyIp, IgnoreIp):
    try:

        winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, enable)
        winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ, proxyIp)
        winreg.SetValueEx(key, "ProxyOverride", 0, winreg.REG_SZ, IgnoreIp)
    except Exception as e:
        print("ERROR: " + str(e.args))
    finally:
        None


# 开启，定义代理服务器ip及端口，忽略ip内容(分号分割)
def enableProxy():
    proxyIP = "http://proxy.piccnet.com.cn:3128"
    IgnoreIp = "10.134.*;10.*;11.*;4a.*;sso.*;proxy.piccnet.com.cn;172.*;oa.*;web.*;mail.picc.com.cn;*.piccnet.com.cn;localhost*;*.piccad.intra;*.piccnet.com.cn;48.*;44.*;40.*;76.*;68.*;18.*;22.*;72.*;192.*;autoclaim.picc.com.cn;12.*;26.*;30.*;32.*;88.*;60.*;46.*;*.piccad.intra;*.piccnet.com.cn*.piccad.intra;*.piccnet.com.cn*.piccad.intra;*.piccnet.com.cn;10.133.*;10.8.*;76.*;35.*;36*;44*;10.8.*;windows10.microdone.cn"
    setProxy(1, proxyIP, IgnoreIp)
    print("开启人保代理成功")


# 关闭清空代理
def disableProxy():
    setProxy(0, "", "")
    print("关闭代理成功")


def main():
    # 手动输入选择的方式
    # place = input("请输入是否开启代理（1开启，2关闭）：\n")
    # try:
    #     if place == "2":
    #         disableProxy()
    #         time.sleep(2)  # 强制等待2秒,为了看到控制台文字
    #     elif place == "1":
    #         enableProxy()
    #         time.sleep(2)  # 强制等待2秒,为了看到控制台文字
    #     else:
    #         main()
    # except Exception as e:
    #     print("ERROR: " + str(e.args))
    # finally:
    #     pass

    # 自动选择的方式
    ps = ProxyServer()
    ipPort = ps.get_server_form_Win()
    if ipPort == "http://proxy.piccnet.com.cn:3128":
        disableProxy()
    else:
        enableProxy()
    time.sleep(2)  # 强制等待2秒,为了看到控制台文字

if __name__ == '__main__':
    main()
